package com.hframe.typefilter;

import org.apache.log4j.Logger;

import java.security.MessageDigest;

public class SHAEncoder implements FilterRef<String, Object> {
	static Logger log = Logger.getLogger(SHAEncoder.class);

	@Override
	public String filter(Object object) {
		if (object instanceof byte[]) {
			return encoder((byte[]) object);
		}
		return null;
	}

	public static String encoder(String src) {
		return encoder(src.getBytes());
	}

	public static String encoder(byte[] b) {
		StringBuffer hexString = new StringBuffer();
		try {
			MessageDigest digest = MessageDigest.getInstance("SHA");
			digest.update(b);
			byte msgDigest[] = digest.digest();
			for (byte val : msgDigest) {
				String shaHex = Integer.toHexString(val & 0xFF);
				if (shaHex.length() < 2)
					hexString.append(0);
				hexString.append(shaHex);
			}
		} catch (Exception e) {
			log.error(e, e);
		}
		return hexString.toString();
	}
}